package com.huicoo.forestmanager.ui.web;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.base.BaseApplication;
import com.huicoo.forestmanager.base.BaseFragment;
import com.huicoo.forestmanager.network.HttpService;
import com.huicoo.forestmanager.others.Constants;
import com.huicoo.forestmanager.others.MediaEvent;
import com.huicoo.forestmanager.others.WebRefreshEvent;
import com.huicoo.forestmanager.ui.login.LoginActivity;
import com.huicoo.forestmanager.ui.media.CaptureVideoActivity;
import com.huicoo.forestmanager.ui.media.TakePhotoActivity;
import com.huicoo.forestmanager.ui.patrol.PatrolRecordActivity;
import com.huicoo.forestmanager.ui.patrol.fireAlarm.FireAlarmActivity;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.ForestCampTaskActivity;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.contract.ForestCampTaskVerifyEventContract;
import com.huicoo.forestmanager.ui.qr_helper.activity.CaptureActivity;
import com.huicoo.forestmanager.util.AttachmentHelper;
import com.huicoo.forestmanager.util.DisplayUtil;
import com.huicoo.forestmanager.util.GCJ2WGS;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.SharedPreferenceUtil;
import com.huicoo.forestmanager.util.StringUtil;
import com.huicoo.forestmanager.util.SystemFunctionUtils;
import com.huicoo.forestmanager.util.WeakHandler;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.huicoo.forestmanager.widget.LoadingDialog;
import com.huicoo.forestmanager.widget.update.AppUpdateDownInfo;
import com.huicoo.forestmanager.widget.update.DownManager;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static android.app.Activity.RESULT_OK;

/**
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2019/4/12	    Administrator
 * 通用的 web activity
 * 接收参数：
 * String url           跳转链接
 */
public class CustomWebFragment extends BaseFragment implements Handler.Callback, AMapLocationListener {
    private String UUID = CustomUtils.getUUID();
    protected int FILECHOOSER_RESULTCODE = 210;// 表单的结果回调
    protected int SCANNIN_GREQUEST_CODE = 310; //扫码的结果码

    @BindView(R.id.web_view)
    WebView web_view;
    @BindView(R.id.pb_currency_web)
    ProgressBar pb_currency_web;
    @BindView(R.id.back)
    View back;

    @OnClick(R.id.iv_back)
    public void clickBack() {
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    private static final String APP_CACAHE_DIRNAME = "/webcache";
    private String mUrl;
    private boolean isDealBack; //是否让h5处理返回按钮

    private LoadingDialog loadingDialog;
    private WeakHandler handler;

    private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private Uri attachmentUri;

    //声明locationClient对象
    private AMapLocationClient mLocationClient;
    //声明mLocationOption对象
    private AMapLocationClientOption mLocationOption;
    private boolean isRequestLocation;
    private double lastLatitude = -1, lastLongitude = -1;

    private OnCustomWebListener onCustomWebListener;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_custom_web;
    }

    public static CustomWebFragment getInstance(String url) {
        Bundle argument = new Bundle();
        argument.putString("url", url);
        CustomWebFragment fragment = new CustomWebFragment();
        fragment.setArguments(argument);
        return fragment;
    }

    @Override
    protected void initView() {
        if (getActivity() != null) {
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        }

        initWeb();

        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(getActivity());
        }

        handler = new WeakHandler(this);

        initLocation();

        EventBus.getDefault().register(this);
    }

    private void initWeb() {
        //获取webSetting
        WebSettings webSettings = web_view.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        // 设置可以支持缩放
        webSettings.setSupportZoom(true);
        //缩放控制器
        //webSettings.setBuiltInZoomControls(true);
        //https图片问题
        if (Build.VERSION.SDK_INT >= 21) {
            webSettings.setMixedContentMode(0);
        }
        //自适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //设置 缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //开启 database storage API 功能
        webSettings.setDatabaseEnabled(true);
        String cacheDirPath = getActivity().getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        LogUtils.v("gogogo cache path = " + cacheDirPath);
        //设置数据库缓存路径
        webSettings.setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        webSettings.setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        webSettings.setAppCacheEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //启用地理定位
        webSettings.setGeolocationEnabled(true);
        //设置定位的数据库路径
        String dir = getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setGeolocationDatabasePath(dir);
        //设置WebView是否需要用户手势才能播放媒体。默认true。false可以自动播放
        webSettings.setMediaPlaybackRequiresUserGesture(false);
        //设置WebViewClient和WebChromeClient
        web_view.setWebViewClient(new CustomWebViewClient());
        web_view.setWebChromeClient(new CustomWebChromeClient());

        web_view.clearCache(true);
        web_view.clearHistory();

        Bundle initBundle = getArguments();
        if (initBundle != null) {
            //网页地址
            mUrl = initBundle.getString("url", "");
            web_view.loadUrl(mUrl);
        }
    }

    //Web视图
    private class CustomWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (dealProtocol(url)) {
                return true;
            }

            LogUtils.v("gogogo override url-mUrl = " + url + "  --  " + mUrl);
            if (TextUtils.equals(url, mUrl)) {
                view.reload();
            } else {
                String nextUrl = CustomUtils.urlAddParams(getActivity(), url);
                LogUtils.v("gogogo override url-nextUrl = " + url + "  --  " + nextUrl);
                Bundle bundle = new Bundle();
                bundle.putString("url", nextUrl);
                Intent intent = new Intent(getActivity(), CustomWebActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            return true;
        }

        //清除缓存用
        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LogUtils.v("gogogo on received page start");
            isDealBack = true;

            // 播放视频显示返回按钮
//            if (mUrl.contains("h5/video.html")) {
//                back.setVisibility(View.VISIBLE);
//            } else {
//                back.setVisibility(View.GONE);
//            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            //判断是否需要清除历史记录
            if (web_view.getProgress() == 100) {
                setPbDismiss();
            }
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {
            super.onReceivedError(webView, i, s, s1);
            LogUtils.v("gogogo on received error 1");
            isDealBack = false;
        }

        @Override
        public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
            super.onReceivedError(webView, webResourceRequest, webResourceError);
            LogUtils.v("gogogo on received error 2");
            isDealBack = false;
        }
    }

    //ChromeClient
    public class CustomWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            pb_currency_web.setProgress(newProgress);
            if (newProgress == 100) {
                setPbDismiss();
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            //初始化uri
            File imageStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ForestManager/attachment/");
            // Create the storage directory if it does not exist
            if (!imageStorageDir.exists()) {
                imageStorageDir.mkdirs();
            }

            //根据mode处理事件
            if (fileChooserParams.getMode() == 0) {
                if (fileChooserParams.getAcceptTypes() != null && fileChooserParams.getAcceptTypes().length > 0) {
                    String acceptType = fileChooserParams.getAcceptTypes()[0];
                    if (acceptType.contains("video")) {
                        gotoTakeVideo();
                    } else if (acceptType.contains("image")) {
                        gotoTakePhoto();
                    }
                }
            } else {
                File file = new File(imageStorageDir + File.separator + "ATTACHMENT_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    attachmentUri = FileProvider.getUriForFile(getActivity().getApplicationContext(), "com.huicoo.forestmanager" + ".fileProvider", file);
                } else {
                    attachmentUri = Uri.fromFile(file);
                }
                showPhotoAction();
            }
            return true;
        }


        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            take(null);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            take(acceptType);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            take(acceptType);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String s, GeolocationPermissionsCallback callback) {
            callback.invoke(s, true, false);
            super.onGeolocationPermissionsShowPrompt(s, callback);
        }
    }

    //加载完成，进度条消失
    private void setPbDismiss() {
        ObjectAnimator animation = ObjectAnimator.ofFloat(pb_currency_web, "alpha", 1, 0);
        animation.setDuration(1000);
        animation.start();
    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(getActivity());
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mLocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒
        mLocationOption.setInterval(3000);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
    }

    @Override
    public void onDestroy() {
        web_view.removeAllViews();
        web_view.destroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.unRegisterLocationListener(this);
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
        stopDownloadFile();
        super.onDestroy();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                if (result != null) {
                    String path = getPath(getContext(), result);
                    Uri uri = Uri.fromFile(new File(path));
                    mUploadMessage.onReceiveValue(uri);
                } else {
                    mUploadMessage.onReceiveValue(attachmentUri);
                }
                mUploadMessage = null;
            }
        }
        //扫码结果
        else if (requestCode == SCANNIN_GREQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    String scanResult = bundle.getString("result", "");
                    LogUtils.v("gogogo scanResult = " + scanResult);
                    web_view.loadUrl("javascript:comopt.setScanResult('" + scanResult + "')");
                }
            }
        }

    }

    private void gotoTakePhoto() {
        Intent intent = new Intent(getContext(), TakePhotoActivity.class);
        getContext().startActivity(intent);
    }

    private void gotoTakeVideo() {
        Intent intent = new Intent(getContext(), CaptureVideoActivity.class);
        getContext().startActivity(intent);
    }

    @SuppressWarnings("null")
    @TargetApi(Build.VERSION_CODES.BASE)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }

        Uri[] results = null;

        if (resultCode == RESULT_OK) {

            if (data == null) {

                results = new Uri[]{attachmentUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();

                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        if (results != null) {
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        } else {
            results = new Uri[]{attachmentUri};
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }

    }


    private void take(String acceptType) {
        boolean isVideo = false;
        String fileSuffix = ".jpg";
        if (acceptType != null && acceptType.contains("video")) {
            fileSuffix = ".mp4";
            isVideo = true;
        }

        File imageStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ForestManager/attachment/");
        // Create the storage directory if it does not exist
        if (!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "ATTACHMENT_" + String.valueOf(System.currentTimeMillis()) + fileSuffix);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            attachmentUri = FileProvider.getUriForFile(getActivity().getApplicationContext(), "com.huicoo.forestmanager" + ".fileProvider", file);
        } else {
            attachmentUri = Uri.fromFile(file);
        }

        if (isVideo) {
            gotoTakeVideo();
        } else {
            gotoTakePhoto();
        }

    }

    private void showPhotoAction() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, FILECHOOSER_RESULTCODE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void captureMediaSuccessEvent(MediaEvent event) {
        if (mUploadCallbackAboveL == null && mUploadMessage == null) {
            return;
        }
        LogUtils.v("gogogo on success event web = " + event.type + " -- " + event.filePath);
        if (event.filePath == null) {
            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            } else if (attachmentUri != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            return;
        }
        String filePath = event.filePath;
        File file = new File(filePath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            attachmentUri = FileProvider.getUriForFile(getActivity().getApplicationContext(), "com.huicoo.forestmanager" + ".fileProvider", file);
        } else {
            attachmentUri = Uri.fromFile(file);
        }
        LogUtils.v("gogogo attachment uri = " + attachmentUri.getPath());
        if (mUploadCallbackAboveL != null) {
            Uri[] results = new Uri[]{attachmentUri};
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        } else if (attachmentUri != null) {
            mUploadMessage.onReceiveValue(attachmentUri);
            mUploadMessage = null;
        }
    }

    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }


    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private boolean dealProtocol(String url) {
        LogUtils.v("gogogo deal protocol url = " + url);
        if (url.startsWith("tel:")) {
            String phone = url.replace("tel:", "");
            AlertDialog dialog = new AlertDialog.Builder(getActivity())
                    .setTitle("提醒")
                    .setMessage(String.format("是否拨打电话：%s", phone))
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SystemFunctionUtils.dial(getActivity(), phone);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create();
            dialog.show();
            return true;
        } else if (url.startsWith("fmandroid://")) {
            String goNative = url.replace("fmandroid://", "");
            LogUtils.v("gogogo deal protocol goNative = " + goNative);
            String params = "";
            if (goNative.contains("!!!")) {
                String[] temps = goNative.split("!!!");
                goNative = temps[0];
                params = temps[1];
            }
            switch (goNative) {
                case "back":
                    if (web_view.canGoBack()) {
                        web_view.goBack();
                    } else {
                        if (getActivity() != null) {
                            getActivity().onBackPressed();
                        }
                    }
                    break;
                case "startPatrol":
                    Intent intent = new Intent(getActivity(), ForestCampTaskActivity.class);
                    startActivity(intent);
                    break;
                case "reportWarning":
                    FireAlarmActivity.start(getActivity());
                    break;
                case "fireAlarm":
                    FireAlarmActivity.start(getActivity(), 1);
                    break;
                case "update":
                    checkUpdateVersion();
                    break;
                case "logout":
                    logout();
                    break;
                case "switchAccount":
                    switchAccount();
                    break;
                case "openMenu":
                    if (onCustomWebListener != null) {
                        onCustomWebListener.openMenu();
                    }
                    break;
                case "patrolRecord":
                    gotoPatrolRecord();
                    break;
                case "scanQRCode":
                    startScan();
                    break;
                case "refresh":
                    EventBus.getDefault().post(new WebRefreshEvent(UUID));
                    break;
                case "reload":
                    web_view.reload();
                    break;
                case "location":
                    nativeLocation();
                    break;
                case "video":
                    try {
                        tryToPlayVideo(params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
            return true;
        } else {
            return false;
        }
    }

    private void switchAccount() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        AlertDialog logoutDialog = builder.setTitle("提醒")
                .setMessage("您确定要注销吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        logout();
                    }
                }).setNegativeButton("取消", null).create();
        logoutDialog.show();
    }

    private void logout() {
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.unbindAccount(new CommonCallback() {
            @Override
            public void onSuccess(String s) {
                Log.d(BaseApplication.TAG, "解绑账号成功");
            }

            @Override
            public void onFailed(String s, String s1) {
                Log.d(BaseApplication.TAG, "解绑账号失败");
            }
        });


        SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.TOKEN, "");
        SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.USER_ID, "");
        SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.USER_REAL_NAME, "");
        SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.USER_PASSWORD, "");
        if (getActivity() != null) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            getActivity().startActivity(intent);
            getActivity().finish();
        }
    }

    private void startScan() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), CaptureActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
    }

    private void gotoPatrolRecord() {
        PatrolRecordActivity.start(getActivity());
    }

    private void nativeLocation() {
        if (loadingDialog != null) {
            loadingDialog.show();
        }

        if (lastLatitude == -1 && lastLongitude == -1) {
            mLocationClient.startLocation();
            isRequestLocation = true;
        } else {
            responseLocation(lastLatitude, lastLongitude);
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            lastLatitude = aMapLocation.getLatitude();
            lastLongitude = aMapLocation.getLongitude();
            LogUtils.v("gogogo on location changed = " + lastLatitude + "  --  " + lastLongitude);
            if (isRequestLocation) {
                responseLocation(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                isRequestLocation = false;
            }
        }
    }

    private void responseLocation(double mLatitude, double mLongitude) {
        //定位成功回调信息，设置相关消息
        HashMap<String, Double> result = GCJ2WGS.delta(mLatitude, mLongitude);
        String js = "javascript:comopt.setLocation('" + result.get("lon") + "," + result.get("lat") + "')";
        LogUtils.v("gogogo web get native location js = " + js);
        web_view.loadUrl(js);
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    private void tryToPlayVideo(String path) {
        String fileName = StringUtil.getUrlParam(path, "filename");
        File file = new File(AttachmentHelper.getFilePath(fileName));
        if (file.exists()) {
            playVideo(file.getAbsolutePath());
        } else {
            if (loadingDialog != null) {
                loadingDialog.show();
            }
            download(path, fileName);
        }
    }

    // 播放视频
    private void playVideo(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Context context = getContext();
        Dialog dialog = new Dialog(context, R.style.PlayVideoDialog);
        dialog.setCanceledOnTouchOutside(false);
        //创建video view
        RelativeLayout relativeLayout = new RelativeLayout(context);
        VideoView mVideoView = new VideoView(context);
        mVideoView.setVideoPath(path);
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                LogUtils.v("gogogo play video complete");
                dialog.dismiss();
            }
        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                LogUtils.v("gogogo play video fail");
                dialog.dismiss();
                boolean isDelete = AttachmentHelper.deleteFile(path);
                LogUtils.v("gogogo delete file = " + isDelete);
                ToastUtils.show("视频播放异常，请重试");
                return false;
            }
        });
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        relativeLayout.addView(mVideoView, layoutParams);
        //dialog添加view
        ViewGroup.LayoutParams rootLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.setContentView(relativeLayout, rootLayoutParams);
        Window mWindow = dialog.getWindow();
        if (mWindow != null) {
            WindowManager.LayoutParams lp = mWindow.getAttributes();
            int mScreenWidth = DisplayUtil.getScreenWidth(context);
            int mScreenHeight = DisplayUtil.getScreenHeight(context);
            lp.width = mScreenWidth; // 宽度
            lp.height = (int) (mScreenHeight * 0.6); // 高度
            mWindow.setAttributes(lp);
        }
        dialog.show();
        mVideoView.start();
    }

    //视频附件下载
    private Thread downloadThread;

    private void download(String fileUrl, String fileName) {
        retrofit2.Call<ResponseBody> call = HttpService.getInstance().downloadFile(fileUrl);
        call.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull retrofit2.Call<ResponseBody> call, @NonNull retrofit2.Response<ResponseBody> response) {
                if (response.body() != null) {
                    LogUtils.v("gogogo download file result = " + response.message() + "  length  " + response.body().contentLength() + "  type " + response.body().contentType());
                    if (response.body().contentLength() <= 0) {
                        ToastUtils.show("附件下载失败，请检查附件地址是否正确");
                        return;
                    }
                    ToastUtils.show("正在下载附件");
                    //建立一个文件
                    File file = AttachmentHelper.createFile(fileName);
                    //下载文件放在子线程
                    downloadThread = new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            //保存到本地
                            AttachmentHelper.writeFile2Disk(response, file, new ForestCampTaskVerifyEventContract.FileDownloadCallBack() {
                                @Override
                                public void onLoading(final long current, final long total) {
                                    if (current >= total) {
                                        if (file != null) {
                                            ToastUtils.show("下载完成");
                                            if (loadingDialog != null) {
                                                loadingDialog.dismiss();
                                            }
                                            Message msg = new Message();
                                            msg.what = 333;
                                            msg.obj = file.getAbsolutePath();
                                            handler.sendMessageDelayed(msg, 300);
                                        }
                                    }
                                }
                            });

                        }
                    };
                    downloadThread.start();

                } else {
                    ToastUtils.show("请求失败，请重试");
                }
            }

            @Override
            public void onFailure(@NonNull retrofit2.Call<ResponseBody> call, @NonNull Throwable t) {
                //数据请求失败
                t.printStackTrace();
                ToastUtils.show("请求失败，请重试");
            }
        });
    }

    //中断下载线程
    private void stopDownloadFile() {
        if (downloadThread != null && !downloadThread.isInterrupted()) {
            downloadThread.interrupt();
        }
        downloadThread = null;
    }

    //软件更新相关
    private static final int REQUEST_EXTERNAL_STORAGE = 101;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private DownManager downManager;

    private void toUpdateVersion(AppUpdateDownInfo info) {
        if (downManager == null && getActivity() != null) {
            downManager = new DownManager((AppCompatActivity) getActivity());
            String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ForestManager/apk/";
            File root = new File(rootPath);
            if (!root.exists()) {
                root.mkdirs();
            }
            String downloadPath = rootPath + "ForestManager_" + info.version + ".apk";
            downManager.setDownInfo(info, downloadPath, false);
            downManager.setOnPermissionListener(new DownManager.OnPermissionListener() {
                @Override
                public void noPermission() {
                    if (getActivity() != null) {
                        ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                    }
                }
            });
        }
        downManager.showAppUpdateDialog();
    }

    private AppUpdateDownInfo dealDownInfo(String version, String downloadUrl, String description) {
        AppUpdateDownInfo info = new AppUpdateDownInfo();
        info.version = version;
        info.downloadUrl = downloadUrl;
        info.description = description;
        return info;
    }

    private void checkUpdateVersion() {
        String url = "http://47.110.80.118/CommSvc/GetValue.aspx?type=checksoftupdated&key=ForestManager_sj_" + CustomUtils.getBaseUrlKey() + "&format=json&version=" + CustomUtils.getAppVersionName(getActivity());
        LogUtils.v("gogogo get new version url = " + url);
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                Message msg = new Message();
                msg.what = 200;
                msg.obj = response.body();
                handler.sendMessage(msg);
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                Message msg = new Message();
                msg.what = 500;
                handler.sendMessage(msg);
            }

        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 200:
                try {
                    if (loadingDialog != null) {
                        loadingDialog.dismiss();
                    }
                    if (msg.obj != null) {
                        ResponseBody body = (ResponseBody) msg.obj;
                        String json = body.string();
                        LogUtils.v("gogogo get new version result = " + json);
                        if (!TextUtils.isEmpty(json)) {
                            JSONObject jsonObject = new JSONObject(json);
                            int State = jsonObject.optInt("State", 0);
                            String Msg = jsonObject.optString("Msg", "");
                            if (State == 1) {
                                String Version = jsonObject.optString("Version", "");
                                String Desc = jsonObject.optString("Desc", "");
                                if (!TextUtils.isEmpty(Version)) {
                                    String DownloadUrl = "http://47.110.80.118/CommSvc/GetValue.aspx?type=getnewestsoft&key=forestmanager_sj_" + CustomUtils.getBaseUrlKey() + "&version=" + Version;
                                    toUpdateVersion(dealDownInfo(Version, DownloadUrl, Desc));
                                }
                            } else {
                                ToastUtils.show(TextUtils.isEmpty(Msg) ? "获取版本更新信息失败" : Msg);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.show("获取版本更新信息失败");
                }
                break;
            case 500:
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                ToastUtils.show("获取版本更新信息失败");
                break;
            case 333:
                LogUtils.v("gogogo handler message = " + (String) (msg.obj));
                playVideo((String) msg.obj);
                break;
            default:
                break;
        }
        return false;
    }

    public interface OnCustomWebListener {
        void openMenu();
    }

    public void setOnCustomWebListener(OnCustomWebListener onCustomWebListener) {
        this.onCustomWebListener = onCustomWebListener;
    }

    public boolean dealWebBack() {
        if (isDealBack) {
            LogUtils.v("gogogo deal web back");
            web_view.loadUrl("javascript:comopt.physicalBack()");
            return true;
        }
        return false;
    }

    public void refresh() {
        web_view.reload();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void webRefreshEvent(WebRefreshEvent event) {
        if (!TextUtils.equals(event.UUID, UUID)) {
            refresh();
        }
    }

}
